import useUserInfo from '@/store/useUserInfo'
import { useApi } from '@/api'
import { SmsType } from '@global/types'
import dayjs from '@/utils/dayjs'
import { onMounted, reactive, toRefs, watch } from 'vue'

export default () => {
  const api = useApi()

  const state = reactive({
    /** 剩余可发送短信的时间 */
    leftTime: 0
  })
  onMounted(() => {
    const lastSendTime = dayjs(useUserInfo().lastSendTime) // 获取上次发送的短信的时间
    state.leftTime = lastSendTime.diff(dayjs(), 's')
  })
  watch(
    () => state.leftTime,
    time => {
      if (time > 0) setTimeout(() => state.leftTime--, 1000)
    }
  )

  const sendSmsHandler = async ({ phone, type }: { phone: string; type: SmsType }) => {
    const lastSendTime = dayjs().add(1, 'm').valueOf()
    useUserInfo().$patch({ lastSendTime })
    state.leftTime = 60
    await api.post('/sms', { phone, type })
  }

  return {
    ...toRefs(state),
    /** 发送短信 */
    sendSmsHandler
  }
}
